import { Controller } from "egg";
import { mapKeys, camelCase } from "lodash";

export default class PackageController extends Controller {
  public async list(ctx) {
    const page = 1;
    const { count, rows: list } = await ctx.model.Package.findAndCountAll({
      include: [
        {
          attributes: [],
          model: ctx.model.Version,
          required: false,
          include: [
            {
              attributes: [],
              model: ctx.model.App,
              required: false,
              subQuery: false,
              include: [
                {
                  attributes: [],
                  model: ctx.model.Org,
                  required: false,
                  subQuery: false
                }
              ]
            }
          ]
        }
      ],
      attributes: [
        ["id", "packageId"],
        ["package_name", "packageName"],
        [ctx.model.col("Version.version_name"), "versionName"],
        [ctx.model.col("`Version->App`.app_name"), "appName"],
        [ctx.model.col("`Version->App->Org`.id"), "orgId"],
        ["remark", "remark"],
        "status",
        ["next_status", "nextStatus"],
        ["create_time", "createTime"],
        ["modify_time", "modifyTime"]
      ],
      offset: (page - 1) * 10,
      limit: 10,
      subQuery: false
    });
    ctx.body = {
      success: true,
      data: {
        count,
        list
      }
    };
  }

  public async findAll(ctx) {
    const page = 1;
    const list = await ctx.model.Package.findAll({
      include: [
        {
          attributes: [],
          model: ctx.model.Version,
          required: false,
          include: [
            {
              attributes: [],
              model: ctx.model.App,
              required: false,
              subQuery: false,
              include: [
                {
                  attributes: [],
                  model: ctx.model.Org,
                  required: false,
                  subQuery: false
                }
              ]
            }
          ]
        }
      ],
      attributes: [
        ["id", "packageId"],
        ["package_name", "packageName"],
        [ctx.model.col("Version.version_name"), "versionName"],
        [ctx.model.col("`Version->App`.app_name"), "appName"],
        [ctx.model.col("`Version->App->Org`.id"), "orgId"],
        ["remark", "remark"],
        "status",
        ["next_status", "nextStatus"],
        ["create_time", "createTime"],
        ["modify_time", "modifyTime"]
      ]
    });
    ctx.body = {
      success: true,
      list: list.map(r =>
        mapKeys(r.get(), (_v, k) => {
          return camelCase(k);
        })
      )
    };
  }

  // 发布，发布后会将同版本下其他所有包撤回，更改其状态为 "已失效"，并将此版本更新为 "生效中"
  public async promote(ctx) {
    ctx.body = {};
  }

  // 创建过程几部都存在前端页面，一揽子通过此接口提交
  public async create(ctx) {
    ctx.body = {};
  }

  // 更新包信息
  public async update(ctx) {
    ctx.body = {};
  }
}
